package org.idea.qiyu.framework.rocketmq.config.producer;

import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.idea.qiyu.framework.rocketmq.config.excpetion.MQException;
import org.idea.qiyu.framework.rocketmq.config.serializer.Serializer;
import org.springframework.stereotype.Component;

/**
 * @Author linhao
 * @Date created in 9:52 下午 2021/7/1
 */
@Component
public class MqProducerTemplate<T> {

    private String topic;

    private String tag;

    private IMQProducerFactory producerFactory;

    private Serializer serializer;

    public SendResult send(T t) {
        SendResult sendResult = null;
        try {
            sendResult = producerFactory.createMQProducer().send(createMessage(topic,tag,t));
        }catch (Exception e){
            throw new MQException(e);
        }
        return sendResult;
    }

    private Message createMessage(String topic,String tag, T t) {
        return new Message(topic,tag, serializer.serializer(t));
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public IMQProducerFactory getProducerFactory() {
        return producerFactory;
    }

    public void setProducerFactory(IMQProducerFactory producerFactory) {
        this.producerFactory = producerFactory;
    }

    public Serializer getSerializer() {
        return serializer;
    }

    public void setSerializer(Serializer serializer) {
        this.serializer = serializer;
    }
}
